package com.wudizaba.microservicesdemolistener.listener;

import com.wudizaba.microservicesdemocommon.constant.MqttConstant;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class DeviceListener {




    @Bean
    public void mattDeviceListener() {

        try {
            MqttClient mqttClient = new MqttClient(MqttConstant.BROKER, MqttConstant.SUBSCRIBE_CLIENT_ID);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(MqttConstant.USERNAME);
            options.setPassword(MqttConstant.PASSWORD.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);

            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    log.error(cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    String messageStr = new String(message.getPayload());
                    log.info("messageStr = " + messageStr);
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    log.info(token.toString());
                }
            });

            mqttClient.connect(options);
            mqttClient.subscribe(MqttConstant.TOPIC_DETECT_DATA, 2);
        } catch (MqttException e) {
            log.error(e.getMessage());
        }

    }


//    public void receiveMessage() {
//        // 从redis中获取数据
//        CompletableFuture<List<DeviceData>> mqttCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            String message = redisTemplate.opsForValue().get(MqttConstant.TOPIC_DETECT_DATA + MqttConstant.QoS_2);
//            while (!StringUtils.isEmpty(message)) {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    log.error(ExceptionsConstant.EXCEPTION_MESSAGE, e);
//                }
//            }
//            return JSONObject.parseArray(message, DeviceData.class);
//        });
//        List<DeviceData> deviceData = mqttCompletableFuture.join();
//        System.out.println("deviceData = " + deviceData);
//        deviceDataMapper.insertDeviceDataList(deviceData);
//
//    }
}
